// const app = getApp()
const util = require('../../utils/util.js')
const App = getApp()
const Dialog = require('tdesign-miniprogram/dialog/index')
const PAY_TYPE = {
  CASH: 1,
  WECHAT: 21
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navStyle: [],
    address: null,
    goodsNum: '',
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    num: 0,
    count: 0,
    cart_ids: [],
    text: '没有滑动',
    goPay: 1, //0加入购物车；1支付确认；2支付成功
    daiOrder: {
      // member_card_list: [ //用户会员卡
      //     {
      //         "id": 1, // 用户会员卡ID，如果使用此卡结算，传入此值
      //         "member_id": 1,
      //         "card_id": 41,
      //         "card_type": "3",
      //         "discount": 90,
      //         "card_name": "白银plus会员", // 会员卡名称
      //         "money": "2000.00", //此会员剩余金额
      //         "member_card_goods_discount": 1497.6, //使用此会员卡商品折后金额
      //         "member_card_discount": "白银plus会员9折",
      //         "is_available": 1 //该会员卡是否可用 ，1可用，0不可用（余额不足）
      //     },
      //     {
      //         "id": 2,
      //         "member_id": 1,
      //         "card_id": 43,
      //         "card_type": "3",
      //         "discount": 70,
      //         "card_name": "钻石PLUS会员", // 会员卡名称
      //         "money": "10000.00", //此会员剩余金额
      //         "member_card_goods_discount": 1164.8, //使用此会员卡商品折后金额
      //         "member_card_discount": "钻石PLUS会员7折"
      //     }
      // ]
    },
    reducePrice: 0, //优惠规则
    // 页面显示
    addressInfo: {},
    selectedCard: 'WECHAT', // 用于存储选中的卡片索引
    member_card_id: 0, //用户使用会员卡id
    cardname: '',
    urlParams: {}
  },
  // 返回购物车页面
  backToshop() {
    console.log('shop')
    wx.switchTab({
      url: '/pages/shopcart/shopcart'
    })
  },
  // 去添加地址
  checkAdr() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/addresslist/addreslist?fromcate=1&cartIds=' + this.data.cart_ids.join(',')
    })
  },
  //获取买家留言的value值
  onInputChange(event) {
    console.log(event, 'event.detail.value')
    this.setData({
      messageValue: event.detail.value
    })
  },
  // 会员卡选择功能
  selectCard(event, cardIndex) {
    let that = this
    // payType == 21是微信支付；1是货到付款，反之储值卡支付
    const payType = event ? event.currentTarget.dataset.pay : cardIndex
    // const cardname = event ? event.currentTarget.dataset.cardname : ''
    // const member_card_id = event ? event.currentTarget.dataset.membercardid : ''
    that.setData({
      selectedCard: payType
      // cardname: cardname,
      // member_card_id: member_card_id
    })
  },
  //去支付
  async handleOrderPay(e) {
    console.log('点击支付，获取订单信息')
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    try {
      //组合体参数
      let address_id = 0
      if (App.globalData.addrId) {
        address_id = App.globalData.addrId
      } else if (that.data.address) {
        address_id = that.data.address.id //没有全局地址使用默认地址
      } else {
        wx.showToast({
          title: '请选择配送地址',
          icon: 'error',
          duration: 1000 //持续的时间
        })
        return false
      }

      let pay_type = PAY_TYPE[this.data.selectedCard]
      let cart_ids = that.data.cart_ids
      let member_card_id = that.data.member_card_id
      let remark = that.data.messageValue || ''
      //支付接口
      const orderParams = {
        cart_ids,
        address_id,
        member_card_id,
        remark,
        pay_type
      }

      wx.login({
        success: (res) => {
          orderParams.code = res.code
          console.log(orderParams)
          if (pay_type === PAY_TYPE.WECHAT) {
            //请求微信支付
            console.log('请求微信支付')
            util.request('/api/order/setV2', orderParams, 'POST').then((res) => {
              const data = res.data.data
              if (res.data.code == 0) {
                // pay_state 1支付失败 30货到付款
                if (data.pay_state == 1) {
                  that.setData({
                    goPay: 1
                  })
                  wx.navigateTo({
                    url: '/pages/statepages/statepages?pay_state=1&cartIds=' + that.data.cart_ids.join(',')
                  })
                  return
                }

                let { signData, paySig, signature } = data.pay_params
                wx.requestCommonPayment({
                  mode: 'retail_pay_goods',
                  signData: signData,
                  paySig: paySig,
                  signature: signature,
                  success: function (res) {
                    console.log(res, 'requestCommonPayment成功回调')
                    if (res.errMsg == 'requestCommonPayment:ok') {
                      that.setData({
                        goPay: 2
                      })
                      // that.onLoad()
                      // 支付成功跳转页面
                      wx.navigateTo({
                        url: '/pages/statepages/statepages?pay_state=0&cartIds=' + that.data.cart_ids.join(',')
                      })
                    }
                  },
                  fail: function (res) {
                    console.log('支付失败', res)
                    wx.showToast({
                      title: '支付失败'
                    })
                    wx.navigateTo({
                      url: '/pages/statepages/statepages?pay_state=1&cartIds=' + that.data.cart_ids.join(',')
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            })
          } else if (pay_type === PAY_TYPE.CASH) {
            //请求货到付款
            const dialogConfig = {
              context: this,
              title: '确认使用货到付款吗？',
              closeOnOverlayClick: true,
              content: '客服会尽快和您联系，确认需求，一经确认，次日送达，无质量问题不退换',
              confirmBtn: '确定',
              cancelBtn: '取消'
            }
            Dialog.default.confirm(dialogConfig).then(() => {
              try {
                util.request('/api/order/setSendOrder', orderParams, 'POST').then((res) => {
                  var data = res.data
                  console.log('请求货到付款', res)
                  if (data.code == 0) {
                    const orderInfo = data.data
                    if (orderInfo.pay_state == 30) {
                      that.setData({
                        goPay: 2
                      })
                      wx.navigateTo({
                        url: '/pages/statepages/statepages?pay_state=30&cartIds=' + that.data.cart_ids.join(',')
                      })
                    } else {
                      wx.showToast({
                        title: '申请失败'
                      })
                      wx.navigateTo({
                        url: '/pages/statepages/statepages?pay_state=30&cartIds=' + that.data.cart_ids.join(',')
                      })
                    }
                  } else {
                    wx.showToast({
                      title: data.msg,
                      icon: 'none'
                    })
                  }
                })
              } catch (error) {
                wx.showToast({
                  title: error.msg,
                  icon: 'none'
                })
              }
            })
          } else {
            // 选择了储值卡
            const dialogConfig = {
              context: this,
              title: '',
              closeOnOverlayClick: true,
              content: '确认使用储值卡支付吗？',
              confirmBtn: '确定',
              cancelBtn: '取消'
            }

            Dialog.default
              .confirm(dialogConfig)
              .then(() => {
                // 确认使用储值卡
                console.log('确认使用储值卡')
                //请求微信支付
                util.request('/api/order/set', orderParams, 'POST').then((res) => {
                  var data = res.data.data
                  if (res.data.code == 0) {
                    if (data.pay_state == 2) {
                      that.setData({
                        goPay: 1
                      })

                      wx.navigateTo({
                        url: '/pages/statepages/statepages?pay_state=0&cartIds=' + that.data.cart_ids.join(',')
                      })
                    } else {
                      wx.requestPayment({
                        timeStamp: data.pay_params.timeStamp.toString(),
                        nonceStr: data.pay_params.nonceStr,
                        package: data.pay_params.package ? data.pay_params.package : '',
                        signType: data.pay_params.signType,
                        paySign: data.pay_params.sign,
                        success: function (res) {
                          console.log(res, '提交订单')
                          if (res.errMsg == 'requestPayment:ok') {
                            that.setData({
                              goPay: 2
                            })
                            // that.onLoad()
                            // 支付成功跳转页面
                            wx.navigateTo({
                              url: '/pages/statepages/statepages?pay_state=0&cartIds=' + that.data.cart_ids.join(',')
                            })
                          }
                        },
                        fail: function (res) {
                          console.log('支付失败', res)
                          wx.showToast({
                            title: '支付失败'
                          })
                          wx.navigateTo({
                            url: '/pages/statepages/statepages?pay_state=1&cartIds=' + that.data.cart_ids.join(',')
                          })
                        },
                        complete: function (res) {
                          console.log('支付完成-', res)
                          var url = that.data.url
                          if (res.errMsg == 'requestPayment:ok') {
                            that.setData({
                              goPay: 2
                            })
                            // that.onLoad()
                          }
                          return
                        }
                      })
                    }
                  } else {
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'none'
                    })
                  }
                })
              })
              .catch(() => {
                // 取消
              })
          }
        }
      })
    } catch (error) {
      wx.showToast({
        title: '支付失败',
        icon: 'error'
      })
      console.log(error)
    }
  },
  //获取地址
  getAddress: function () {
    let that = this
    var addrId = App.globalData.addrId
    if (addrId == 0) {
      //获取默认地址
      util.request('/api/address/index', {}, 'GET').then((res) => {
        var datas = res.data.data
        if (datas.length == 0) return
        datas.forEach((v) => {
          if (v.is_default == 1) {
            that.setData({
              address: v,
              addressInfo: {
                address_info: v.provinceid + v.cityid + v.countryid + v.street,
                phone: v.phone,
                name: v.name
              }
            })
          }
        })
      })
    } else {
      //获取指定地址
      util
        .request(
          '/api/address/index',
          {
            id: addrId
          },
          'GET'
        )
        .then((res) => {
          var datas = res.data.data
          if (datas.length == 0) return
          const adr = datas[0]
          that.setData({
            address: adr,
            addressInfo: {
              address_info: adr.provinceid + adr.cityid + adr.countryid + adr.street,
              phone: adr.phone,
              name: adr.name
            }
          })
        })
    }
  },
  //获取页面信息
  getDatas: function () {
    var that = this
    let cart_ids = that.data.cart_ids
    util
      .request(
        '/api/order/confirmOrder',
        {
          cart_ids
        },
        'POST'
      )
      .then((res) => {
        if (res.data.code != 0) return

        var daiOrder = res.data.data
        let addressInfo = {}
        if (daiOrder.address_info) {
          addressInfo = {
            name: daiOrder.name,
            phone: daiOrder.phone,
            address_info: daiOrder.address_info
          }
        }

        if (daiOrder.goods.length == 0) {
          console.log('购物车列表暂无数据')
        } else {
          that.count(daiOrder.goods)
          that.countNum(daiOrder.goods)

          that.setData({
            daiOrder,
            addressInfo: addressInfo
          })
          // // 模拟的会员数据member_card_list 插入到daiOrder
          // if (that.data.daiOrder) {
          //     that.setData({
          //         ['daiOrder.member_card_list']: member_card_list // 使用方括号语法来设置嵌套属性
          //     });
          // }
        }
      })
  },
  countNum: function (datas) {
    //计算数量
    var that = this
    var allNum = 0
    for (var i = 0; i < datas.length; i++) {
      allNum += parseInt(datas[i].goods_number)
    }
    that.setData({
      num: allNum
    })
  },

  //计算合计金额方法
  count: function (datas) {
    var that = this
    var newCount = 0
    for (var i = 0; i < datas.length; i++) {
      newCount += parseFloat(datas[i].total_price)
    }
    //获取优惠券并减少相应价格
    newCount = newCount - that.data.reducePrice
    that.setData({
      count: newCount.toFixed(2)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onload')
    console.log(options, 'options.cartIds-商品id')
    if (util.isLogin()) {
      this.setData({
        urlParams: options,
        navStyle: App.globalData,
        cart_ids: options.cartIds.split(',')
      })
      this.getDatas()
      this.getAddress()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})
